package com.unipay.user.api;

import com.alibaba.fastjson.JSONObject;
import com.sun.deploy.net.URLEncoder;
import com.unipay.common.helper.JwtHelper;
import com.unipay.common.result.Result;
import com.unipay.common.utils.HttpClientUtils;
import com.unipay.model.user.UserInfo;
import com.unipay.user.service.UserInfoService;
import com.unipay.user.utils.WxConstantPropertiesUtil;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Project: yitong_parent
 * @Author: C.yu
 * @Time: 2023-05-14 15:27:09
 * @Desc: TODO
 */
@Api(tags = "用户微信登录平台API")
// 这里不用@RestController = + @Controller：当扫描二维码，然后回调提交用户信息后，不是返回，而是---跳转页面
@Controller
@RequestMapping("/api/ucenter/wx")
public class WeixinApiController {
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private RedisTemplate redisTemplate;

    // 1、生成微信扫描二维码，返回生成二维码所需要参数（获取微信登录参数）
    @GetMapping("getLoginParam")
    @ResponseBody
    public Result getLoginParam(HttpSession session) {
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("appid", WxConstantPropertiesUtil.WX_OPEN_APP_ID);
            map.put("scope", "snsapi_login");
            String wxOpenRedirectUrl = WxConstantPropertiesUtil.WX_OPEN_REDIRECT_URL;
            wxOpenRedirectUrl = URLEncoder.encode(wxOpenRedirectUrl, "utf-8");
            map.put("redirect_uri", wxOpenRedirectUrl);
            map.put("state", System.currentTimeMillis() + "");
            return Result.ok(map);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }

    // 扫描二维码后，跳转请求地址：http://localhost:8160/api/ucenter/wx/callback?code=061oVqll2JWcjb4eVAll2NN1pA0oVql4&state=1684054172537
    // 2、微信扫描后，回调的方法
    @GetMapping("callback")
    //public Result callback(String code, String state) {
    public String callback(String code, String state) {
        //（1）获取临时票据 code
        System.out.println("code: " + code);
        //（2）TODO 拿着code和微信id和秘钥，请求微信固定地址 ，得到两个值（使用code和appid以及appscrect，换取access_token）
        // %s --- 占位符
        StringBuffer baseAccessTokenUrl = new StringBuffer()
                .append("https://api.weixin.qq.com/sns/oauth2/access_token")
                .append("?appid=%s")
                .append("&secret=%s")
                .append("&code=%s")
                .append("&grant_type=authorization_code");
        String accessTokenUrl = String.format(baseAccessTokenUrl.toString(),
                WxConstantPropertiesUtil.WX_OPEN_APP_ID,
                WxConstantPropertiesUtil.WX_OPEN_APP_SECRET,
                code);
        //（3）使用httpclient请求，这个地址
        try {
            String accessTokenInfo = HttpClientUtils.get(accessTokenUrl);
            System.out.println("accessTokenInfo: " + accessTokenInfo);
            /*
             * {
             *      "access_token": "68_P-58hnQph7HNygbgJDanYG6d0vvXuNYGJJL5FU-cXylgizhQRXJD6O1ZuwPt8tcb-vXMYd5K-s3Z8tQRQ4YW3EY-syYw3709xJDrrqXi-I8",
             *      "expires_in": 7200,
             *      "refresh_token": "68_g7rEmkPoHJqQeg6F1UuIY2RZHl2D_laP9lzgLGePtH5mKXwMJTjqZjvxVpGLSTEoLNr_k6_DTYa2Y8EN5RNB3sIDn4VgdjtOVvwy1u5FqYs",
             *      "openid": "o3_SC5y7YKiIerUOQ9_N7JpZ0dfQ",
             *      "scope": "snsapi_login",
             *      "unionid": "oWgGz1M4haoNv_mRV20A3m7xe7Lg"
             *  }
             */
            // TODO JSON转换：从返回字符串获取两个值 openid  和  access_token
            JSONObject accessTokenJson = JSONObject.parseObject(accessTokenInfo);
            String access_token = accessTokenJson.getString("access_token");
            String openid = accessTokenJson.getString("openid");

            //（4）判断数据库是否存在微信的扫描人信息（根据openid判断）
            UserInfo userInfo = userInfoService.selectWxInfoOpenId(openid);
            if (userInfo == null) {
                // user_info数据库，不存在微信信息
                //（4.1）TODO 拿着openid  和  access_token请求微信地址，得到扫描人信息
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                String userInfoUrl = String.format(baseUserInfoUrl, access_token, openid);
                String wxUserInfo = HttpClientUtils.get(userInfoUrl);
                System.out.println("wxUserInfo: " + wxUserInfo);
                /*
                 * {
                 *      "openid": "o3_SC5y7YKiIerUOQ9_N7JpZ0dfQ",
                 *      "nickname": "C.yu",
                 *      "sex": 0,
                 *      "language": "",
                 *      "city": "",
                 *      "province": "",
                 *      "country": "",
                 *      "headimgurl": "https:\/\/thirdwx.qlogo.cn\/mmopen\/vi_32\/Q0j4TwGTfTJric5ujd1gWWqZqA0fe9hgiae6MjuOtAbcRvIR3C7eRsTs88CqSdvq4aONXNhnUxgib1c44BibBlPo9Q\/132",
                 *      "privilege": [],
                 *      "unionid": "oWgGz1M4haoNv_mRV20A3m7xe7Lg"
                 *  }
                 */
                //（4.2）解析微信扫描人信息：昵称、头像
                JSONObject wxUserInfoJson = JSONObject.parseObject(wxUserInfo);
                String nickname = wxUserInfoJson.getString("nickname");
                String headimgurl = wxUserInfoJson.getString("headimgurl");
                //（4.3）将微信信息，添加至数据库
                userInfo = new UserInfo();
                userInfo.setNickName(nickname);
                userInfo.setOpenid(openid);
                userInfo.setStatus(1);
                userInfoService.save(userInfo);
            }
            //（5）返回：name、openid、token字符串
            Map<String, String> map = new HashMap<>();
            // name：没有nickname，必有手机号（登录的）
            String name = userInfo.getName();
            if (StringUtils.isEmpty(name)) {
                name = userInfo.getNickName();
            }
            if (StringUtils.isEmpty(name)) {
                name = userInfo.getPhone();
            }
            map.put("name", name);
            // TODO 判断userInfo是否有手机号？
            // 如果手机号为空，返回openid；如果手机号不为空，返回openid值是空字符串
            // TODO 前端判断：如果openid不为空，绑定手机号，如果openid为空，不需要绑定手机号
            if (StringUtils.isEmpty(userInfo.getPhone())) {
                map.put("openid", userInfo.getOpenid());
            } else {
                //map.put("openid", "");
                map.put("openid", null);
            }
            // token：
            String token = JwtHelper.createToken(userInfo.getId(), name);
            map.put("token", token);
            return "redirect:" + WxConstantPropertiesUtil.YYGH_BASE_URL + "/weixin/callback?token=" + map.get("token") + "&openid=" + map.get("openid") + "&name=" + URLEncoder.encode(map.get("name"), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
